<script setup>
import { ref, onMounted, computed } from 'vue'
import ApiService from '@/services/ApiService'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { hasPermission } from '@/utils/auth'
import { Plus, Loading } from '@element-plus/icons-vue'

const authStore = useAuthStore()
const users = ref([])
const roles = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const currentUser = ref(null)
const selectedRoles = ref([])
const createUserDialog = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

// 新用户表单
const userForm = ref({
  username: '',
  password: '',
  email: '',
  role: 'viewer' // 默认角色
})

// 检查权限 - 只有管理员可以管理用户
const canManageUsers = computed(() => hasPermission('*'))

// 加载所有用户
const loadUsers = async () => {
  loading.value = true
  try {
    users.value = await ApiService.getUsers()
    loading.value = false
  } catch (error) {
    ElMessage.error('加载用户列表失败')
    loading.value = false
  }
}

// 加载所有角色
const loadRoles = async () => {
  loading.value = true
  try {
    roles.value = await ApiService.getRoles()
    loading.value = false
  } catch (error) {
    ElMessage.error('加载角色列表失败')
    loading.value = false
  }
}

// 加载特定用户的角色
const loadUserRoles = async (userId) => {
  loading.value = true
  try {
    const userRoles = await ApiService.getUserRoles(userId)
    selectedRoles.value = userRoles.map(role => role.id)
    loading.value = false
  } catch (error) {
    ElMessage.error('加载用户角色失败')
    loading.value = false
  }
}

// 打开编辑角色对话框
const openRoleDialog = async (user) => {
  if (!canManageUsers.value) {
    ElMessage.error('您没有管理用户角色的权限')
    return
  }
  
  currentUser.value = user
  await loadUserRoles(user.id)
  dialogVisible.value = true
}

// 打开创建用户对话框
const openCreateUserDialog = () => {
  userForm.value = {
    username: '',
    password: '',
    email: '',
    role: 'viewer'
  }
  createUserDialog.value = true
}

// 创建新用户
const createUser = async () => {
  // 表单验证
  if (!userForm.value.username || !userForm.value.password || !userForm.value.email) {
    ElMessage.warning('请填写所有必填字段')
    return
  }
  
  loading.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 检查用户名是否已存在
    const existingUser = users.value.find(u => u.username === userForm.value.username)
    if (existingUser) {
      ElMessage.error('用户名已存在')
      loading.value = false
      return
    }
    
    // 创建新用户（在实际应用中这里应该调用API）
    const newUser = {
      id: users.value.length + 1,
      username: userForm.value.username,
      password: userForm.value.password,
      email: userForm.value.email,
      avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      role: userForm.value.role
    }
    
    users.value.push(newUser)
    ElMessage.success(`用户 ${newUser.username} 已创建`)
    createUserDialog.value = false
    loading.value = false
  } catch (error) {
    ElMessage.error('创建用户失败')
    loading.value = false
  }
}

// 删除用户
const deleteUser = (user) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${user.username}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    loading.value = true
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 800))
      
      // 从列表中移除用户（实际应用中应该调用API）
      users.value = users.value.filter(u => u.id !== user.id)
      
      ElMessage.success(`用户 ${user.username} 已删除`)
      loading.value = false
    } catch (error) {
      ElMessage.error('删除用户失败')
      loading.value = false
    }
  }).catch(() => {
    // 取消删除
  })
}

// 获取角色的名称
const getRoleName = (roleId) => {
  const role = roles.value.find(r => r.id === roleId)
  return role ? role.name : '未知角色'
}

// 保存用户角色
const saveUserRoles = async () => {
  if (!canManageUsers.value) {
    ElMessage.error('您没有管理用户角色的权限')
    return
  }
  
  loading.value = true
  
  // 模拟API调用 - 在真实环境中这里应该发送请求到后端
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新本地数据 - 这里是模拟，实际应该通过API更新
    const userRole = {
      userId: currentUser.value.id,
      roleIds: selectedRoles.value
    }
    
    // 更新用户的主要角色
    const mainRole = selectedRoles.value.length > 0 ? selectedRoles.value[0] : 'viewer'
    const userIndex = users.value.findIndex(u => u.id === currentUser.value.id)
    if (userIndex !== -1) {
      users.value[userIndex].role = mainRole
    }
    
    ElMessage.success(`用户 ${currentUser.value.username} 的角色已更新`)
    dialogVisible.value = false
    loading.value = false
  } catch (error) {
    ElMessage.error('更新用户角色失败')
    loading.value = false
  }
}

// 计算分页后的用户数据
const paginatedUsers = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return users.value.slice(startIndex, endIndex)
})

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

// 初始化
onMounted(async () => {
  await Promise.all([loadUsers(), loadRoles()])
})
</script>

<template>
  <div class="user-management-container" v-if="canManageUsers">
    <el-card class="user-card">
      <template #header>
        <div class="page-header">
          <div class="page-title">
            <h2>用户管理</h2>
          </div>
          <el-button type="primary" @click="openCreateUserDialog">
            <el-icon style="margin-right: 5px;"><Plus /></el-icon>新建用户
          </el-button>
        </div>
      </template>
      
      <div class="card-body">
        <!-- Loading spinner -->
        <div v-if="loading" class="loading-container">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span class="loading-text">加载中...</span>
        </div>
        
        <!-- User Table -->
        <div v-else class="table-container">
          <el-table 
            :data="paginatedUsers" 
            style="width: 100%" 
            table-layout="fixed"
            :max-height="550"
          >
            <el-table-column prop="id" label="ID" width="70" />
            <el-table-column prop="username" label="用户名" width="120" :show-overflow-tooltip="true" />
            <el-table-column prop="email" label="邮箱" min-width="150" :show-overflow-tooltip="true" />
            <el-table-column prop="role" label="主要角色" width="120">
              <template #default="scope">
                <el-tag 
                  :type="
                    scope.row.role === 'admin' ? 'danger' :
                    scope.row.role === 'manager' ? 'warning' :
                    scope.row.role === 'operator' ? 'success' : 'info'
                  "
                >
                  {{ scope.row.role }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <div class="action-buttons">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="openRoleDialog(scope.row)"
                    class="operation-button"
                  >
                    管理角色
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="deleteUser(scope.row)"
                    :disabled="scope.row.id === 1"
                    class="operation-button"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <!-- Footer pagination -->
      <div class="footer-pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="users.length"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[10, 15, 20, 50]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          prev-text="上一页"
          next-text="下一页"
          :pager-count="5"
        />
      </div>
    </el-card>
    
    <!-- 用户角色编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="`编辑用户角色 - ${currentUser?.username || ''}`"
      width="50%"
    >
      <el-form v-if="currentUser" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="currentUser.username" disabled />
        </el-form-item>
        
        <el-form-item label="邮箱">
          <el-input v-model="currentUser.email" disabled />
        </el-form-item>
        
        <el-form-item label="分配角色">
          <div class="role-description-text">
            选择多个角色时，第一个选择的角色将作为用户的主要角色显示在列表中
          </div>
          <el-checkbox-group v-model="selectedRoles">
            <el-checkbox 
              v-for="role in roles" 
              :key="role.id" 
              :label="role.id"
              border
            >
              <div class="role-checkbox-content">
                <div class="role-name">{{ role.name }}</div>
                <div class="role-description">{{ role.description }}</div>
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUserRoles" :loading="loading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 创建用户对话框 -->
    <el-dialog
      v-model="createUserDialog"
      title="创建新用户"
      width="50%"
    >
      <el-form :model="userForm" label-width="100px">
        <el-form-item label="用户名" required>
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="密码" required>
          <el-input v-model="userForm.password" type="password" show-password placeholder="请输入密码" />
        </el-form-item>
        
        <el-form-item label="邮箱" required>
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="默认角色">
          <el-select v-model="userForm.role" placeholder="请选择默认角色">
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createUserDialog = false">取消</el-button>
          <el-button type="primary" @click="createUser" :loading="loading">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  
  <el-result
    v-else
    icon="error"
    title="权限不足"
    sub-title="很抱歉，您没有权限访问用户管理页面"
  >
    <template #extra>
      <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
    </template>
  </el-result>
</template>

<style scoped>
.user-management-container {
  padding: 16px;
  background-color: #f5f7fa;
  height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.user-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0;
}

.page-title {
  display: flex;
  align-items: center;
}

.page-title h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.card-body {
  flex: 1;
  overflow: auto;
  position: relative;
  padding: 6px 0 60px 0;
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.loading-container .el-icon {
  font-size: 2rem;
  margin-bottom: 10px;
}

.loading-text {
  color: #909399;
}

.table-container {
  height: 100%;
  overflow: auto;
  padding-bottom: 10px;
}

.footer-pagination {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 15px 0;
  background-color: white;
  border-top: 1px solid #EBEEF5;
  z-index: 1;
}

.role-checkbox-content {
  display: flex;
  flex-direction: column;
}

.role-name {
  font-weight: 500;
  font-size: 13px;
}

.role-description {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}

.role-description-text {
  font-size: 13px;
  color: #909399;
  margin-bottom: 16px;
  padding: 8px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.action-buttons {
  display: flex;
  justify-content: flex-start;
  gap: 2px;
  flex-wrap: nowrap;
  white-space: nowrap;
  overflow-x: auto;
}

.action-buttons::-webkit-scrollbar {
  display: none;
}

.action-buttons {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.operation-button {
  padding: 5px 10px;
  font-size: 12px;
  height: 28px;
  line-height: 1;
  margin-left: 0;
  margin-right: 3px;
}

/* 调整卡片头部内边距 */
:deep(.el-card__header) {
  padding: 10px 20px;  /* 将默认的 20px 内边距减半为 10px */
}

/* Table styles */
:deep(.el-table) {
  margin-top: 0;
}

/* El-card styles */
:deep(.el-card) {
  margin-top: 6px;
}

/* Button styles */
:deep(.el-button) {
  border-radius: 4px;
  transition: all 0.3s;
}

/* Optimize add button style */
:deep(.el-button .el-icon) {
  margin-right: 4px;
  font-size: 14px;
}

:deep(.el-button--small) {
  padding: 5px 10px;
  font-size: 12px;
  height: 28px;
  line-height: 1;
  margin-left: 0;
  margin-right: 3px;
}

/* Dialog styles */
:deep(.el-dialog) {
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog__header) {
  padding: 16px;
  margin: 0;
  background-color: #ffffff;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 16px;
  max-height: 75vh;
  overflow-y: auto;
}

:deep(.el-dialog__footer) {
  padding: 12px 16px;
  background-color: #ffffff;
  border-top: 1px solid #ebeef5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* Remove the old pagination container */
.pagination-container {
  display: none;
}

/* Table styles */
:deep(.el-table__fixed-right) {
  height: auto !important;
}

:deep(.el-table__fixed-right .el-table__fixed-body-wrapper) {
  height: auto !important;
  position: absolute;
  top: 0;
  right: 0;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}
</style> 